#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Mosson"
from luffyapi.settings import constants

# 修改用户登录成功的返回值

def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功的返回值
    :param token:
    :param user:
    :param request:
    :return:
    """
    return {
        "token": token,
        "id": user.id,
        "username": user.username,
        "user_credit": user.credit,
        "credit_to_money": constants.CREDIT_MONEY,
    }


def get_user_by_account(account):
    """
    根据账号获取user对象
    :param account: 账号可以使用户名username也可以是手机号mobile
    :return: User对象或者None
    """
    try:
        user = User.objects.filter(Q(username=account)|Q(mobile=account)).first()
    except User.DoesNotExist:
        return None
    else:
        return user



from .models import User
from django.db.models import Q
from django.contrib.auth.backends import ModelBackend

# 用户多条件登录[用户名手机号都可以登录]
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user is not None and user.check_password(password) and user.is_authenticated:
            return user
        else:
            return None


